class ComboBoxItem extends MenuItem {
	// may be change a skin.
}

function AddHistoryArray(s: string, values: string[]): void {
	values.remove(s);
	values.unshift(s);
	if (values.length > 10) {
		values.pop();
	}
}

class ComboBox extends eui.Component {
	input: eui.TextInput;

	btnDown: eui.Image;

	override values: string[] = [];

	constructor() {
		super();
		this.skinName = 'ComboxSkin';
	}

	closeDown(): void {
		this.btnDown.visible = false;
	}

	// 支持编辑器里设置
	prevValues = '';

	override childrenCreated(): void {
		super.childrenCreated();
		if (this.prevValues) {
			this.values = this.prevValues.split(',');
		}
		this.input.touchEnabled = false;
		this.btnDown.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTapDown, this);
		this.input.textDisplay.addEventListener(MainFocus.inputEnterEvent, this.onEnter, this);
	}

	removeCurValue(): void {
		const { text } = this.input;
		this.values.remove(text);
	}

	setValues(values: string[], sel = 0): void {
		this.values = values || [];
		this.input.text = this.values[sel];
	}

	closeContexMenu(): void {
		if (this.menu) {
			MainWindow.ins().contexMenu.clearContexMenu(this.menu);
			this.menu = null;
		}
	}

	menu: ContexMenu;

	onTapDown(): void {
		if (!this.values || this.values.length === 0) return;

		const menu = MainWindow.ins().contexMenu.showContexMenu(
			this.values,
			this.onContexSelect,
			this,
			this.width,
		);

		const sheight = menu.stage.stageHeight;
		const swidth = menu.stage.stageWidth;
		// menu.y += this.height; // add input.height!
		menu.x += this.width;
		if (menu.x + menu.width > swidth) {
			menu.x -= this.width + menu.width;
		}
		const h = menu.getMenuHeight();

		if (menu.y + h > sheight) {
			// ui.msglog('menu.height', h);
			const y = menu.y - h;
			if (y > 0) {
				menu.y = y;
			} else {
				// menu.y = sheight - h;
				menu.setScroll(true);
			}
			// menu.y -= h + this.height;
		}
		this.menu = menu;
	}

	static evtTextChange = 'EVT_COMBOX_CHANGE';

	onContexSelect(text: string): void {
		this.input.text = text;
		this.dispatchEventWith(ComboBox.evtTextChange, true, { text });
	}

	onEnter(): void {
		this.dispatchEventWith(ComboBox.evtTextChange, true, { text: this.input.text });
	}

	disableInput(): void {
		this.input.touchEnabled = false;
		this.input.touchChildren = false;
	}

	getValue(): string {
		return this.input.text;
	}

	setValue(s: string): void {
		this.input.text = s;
	}

	public get text(): string {
		return this.input.text;
	}

	public set text(v: string) {
		this.input.text = v;
	}

	RecordValue(): void {
		const s = this.input.text;
		AddHistoryArray(s, this.values);
	}
}
